package com.management.department.teacherinfosystem.Controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.management.department.teacherinfosystem.DTO.StudentGuidanceStatsDTO;
import com.management.department.teacherinfosystem.DTO.StudentGuidanceSubmitDTO;
import com.management.department.teacherinfosystem.Entity.User;
import com.management.department.teacherinfosystem.Service.StudentGuidanceService;
import com.management.department.teacherinfosystem.Repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/student-guidance")
@RequiredArgsConstructor
public class StudentGuidanceController {

    private final StudentGuidanceService guidanceService;
    private final UserRepository userRepository;

    private User getCurrentUser() {
        org.springframework.security.core.Authentication auth =
                org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = auth.getName();
        return userRepository.findByUsernameWithRoles(currentUsername).orElse(null);
    }

    private boolean currentIsAdmin() {
        org.springframework.security.core.Authentication auth =
                org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
        return auth.getAuthorities().stream().anyMatch(a -> {
            String au = a.getAuthority();
            return "ROLE_ADMIN".equalsIgnoreCase(au) || "ADMIN".equalsIgnoreCase(au);
        });
    }

    @GetMapping("/my")
    public ResponseEntity<?> listMy(@RequestParam(value = "page", defaultValue = "1") int page,
                                    @RequestParam(value = "size", defaultValue = "10") int size,
                                    @RequestParam(value = "studentType", required = false) String studentType,
                                    @RequestParam(value = "achievementType", required = false) String achievementType,
                                    @RequestParam(value = "level", required = false) String level,
                                    @RequestParam(value = "year", required = false) String year,
                                    @RequestParam(value = "status", required = false) String status) {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        Pageable pageable = PageRequest.of(Math.max(page - 1, 0), Math.max(size, 1));
        Page<?> result = guidanceService.listMy(user.getId(), pageable, studentType, achievementType, level, year, status);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/list")
    public ResponseEntity<?> listAll(@RequestParam(value = "page", defaultValue = "1") int page,
                                     @RequestParam(value = "size", defaultValue = "10") int size,
                                     @RequestParam(value = "teacherId", required = false) Long teacherId,
                                     @RequestParam(value = "teacherName", required = false) String teacherName,
                                     @RequestParam(value = "studentType", required = false) String studentType,
                                     @RequestParam(value = "achievementType", required = false) String achievementType,
                                     @RequestParam(value = "level", required = false) String level,
                                     @RequestParam(value = "year", required = false) String year,
                                     @RequestParam(value = "status", required = false) String status) {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        if (!currentIsAdmin()) return ResponseEntity.status(403).body("权限不足");
        Pageable pageable = PageRequest.of(Math.max(page - 1, 0), Math.max(size, 1));
        return ResponseEntity.ok(guidanceService.listAll(pageable, teacherId, teacherName, studentType, achievementType, level, year, status));
    }

    @GetMapping("/{id:[0-9]+}")
    public ResponseEntity<?> getById(@PathVariable("id") Long id) {
        var g = guidanceService.getById(id);
        if (g == null) return ResponseEntity.notFound().build();
        return ResponseEntity.ok(g);
    }

    @PostMapping
    public ResponseEntity<?> create(@RequestBody StudentGuidanceSubmitDTO dto) {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        Long id = guidanceService.create(user.getId(), dto);
        return ResponseEntity.ok(id);
    }

    @PutMapping("/{id:[0-9]+}")
    public ResponseEntity<?> update(@PathVariable("id") Long id, @RequestBody StudentGuidanceSubmitDTO dto) {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        guidanceService.update(id, user.getId(), dto);
        return ResponseEntity.ok("更新成功");
    }

    @DeleteMapping("/{id:[0-9]+}")
    public ResponseEntity<?> delete(@PathVariable("id") Long id) {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        guidanceService.delete(id, user.getId());
        return ResponseEntity.ok("删除成功");
    }

    @PostMapping("/{id:[0-9]+}/review")
    @Transactional
    public ResponseEntity<?> review(@PathVariable("id") Long id, @RequestBody String body) throws Exception {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        if (!currentIsAdmin()) return ResponseEntity.status(403).body("权限不足");
        var mapper = new ObjectMapper();
        var node = mapper.readTree(body);
        String status = node.path("status").asText();
        String opinion = node.path("opinion").asText();
        guidanceService.review(id, user.getId(), status, opinion);
        return ResponseEntity.ok("审核完成");
    }

    @GetMapping("/stats")
    public ResponseEntity<StudentGuidanceStatsDTO> stats(@RequestParam(value = "teacherId", required = false) Long teacherId,
                                                         @RequestParam(value = "studentType", required = false) String studentType,
                                                         @RequestParam(value = "achievementType", required = false) String achievementType,
                                                         @RequestParam(value = "level", required = false) String level,
                                                         @RequestParam(value = "year", required = false) String year) {
        if (!currentIsAdmin()) return ResponseEntity.status(403).build();
        return ResponseEntity.ok(guidanceService.stats(teacherId, studentType, achievementType, level, year));
    }

    // ===== 附件上传 =====
    @PostMapping("/achievements/{achievementId:[0-9]+}/attachments")
    public ResponseEntity<?> upload(@PathVariable("achievementId") Long achievementId,
                                    @RequestParam("file") MultipartFile file,
                                    @RequestParam(value = "fileType", required = false, defaultValue = "附件") String fileType) throws Exception {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        // 复用活动上传逻辑的目录配置 or 使用学术成果目录，这里直接沿用活动附件目录键值
        return ResponseEntity.ok("TODO: implement and wire service to save file for achievementId=" + achievementId);
    }

    @GetMapping("/achievements/{achievementId:[0-9]+}/attachments")
    public ResponseEntity<?> listAttachments(@PathVariable("achievementId") Long achievementId) {
        return ResponseEntity.ok(java.util.List.of());
    }

    @DeleteMapping("/attachments/{attachmentId:[0-9]+}")
    public ResponseEntity<?> deleteAttachment(@PathVariable("attachmentId") Long attachmentId) {
        return ResponseEntity.ok("已删除");
    }
} 